package com.tanhua.interceptor;

import com.alibaba.fastjson.JSON;
import com.tanhua.dubbo.api.LogApi;
import com.tanhua.model.domain.Log;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class LogListener {

    @DubboReference
    private LogApi logApi;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(
                    value = "tanhua.log.queue",
                    durable = "true"
            ),
            exchange = @Exchange(
                    value = "tanhua.log.exchange",
                    type = ExchangeTypes.TOPIC),
            key = {"log.*"})
    )
    public void listenCreate(String message) throws Exception {
        try {
            Map map = JSON.parseObject(message,Map.class);
            map.forEach((k,v)-> System.out.println(k+"--"+v));
            //1、解析MAP获取数据
            Long userId = Long.valueOf(map.get("userId").toString());
            String type = (String) map.get("type");
            String logTime = (String) map.get("logTime");
            //2、保存到数据库
            Log log = new Log(userId,logTime,type);
            logApi.insert(log);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}